package com.pokermind.dse.controller;

import com.pokermind.common.log.PlainLog;
import com.pokermind.common.log.TimeCostLog;
import com.pokermind.common.web.ApiResponse;
import com.pokermind.model.dto.AIAnalysisRequest;
import com.pokermind.model.dto.AIAnalysisResponse;
import com.pokermind.model.enums.ErrorCode;
import com.pokermind.operator.AIAnalysisOperator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * AI Analysis Controller - Simplified Version Implements AI decision analysis interface for real game scenarios
 *
 * @author PokerMind Team
 */
@RestController
@RequestMapping("/api/v2")
@CrossOrigin(origins = "*")
public class AIAnalysisController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(AIAnalysisController.class);

    @Autowired
    private AIAnalysisOperator aiAnalysisOperator;

    /**
     * AI Analysis Interface - Decision recommendation when it's Hero's turn POST /ai/analyze
     */
    @PostMapping("/ai/analyze")
    public ResponseEntity<ApiResponse<AIAnalysisResponse>> requestAIAnalysis(@RequestBody AIAnalysisRequest request) {
        PlainLog log = new TimeCostLog("api", "ai_analysis").put("handRecordId",
                request != null ? request.getHandId() : null)
            .put("playerId", request != null ? request.getPlayerId() : null);  // ✅ 改为 playerId
        try {
            // Simplified parameter validation
            if (request == null || request.getHandId() == null) {
                logger.warn(log.put("op_rslt", "invalid_request").toString());
                return badRequest(ErrorCode.VALIDATION_EMPTY_FIELD);
            }
            // Player ID validation (新API格式)
            if (request.getPlayerId() == null || request.getPlayerId().trim().isEmpty()) {
                logger.warn(log.put("op_rslt", "missing_player_id").toString());
                return badRequest(ErrorCode.AI_HERO_ID_MISSING);  // 复用错误码
            }
            // Hole cards validation (新API格式)
            if (request.getHoleCards() == null || request.getHoleCards().isEmpty()) {
                logger.warn(log.put("op_rslt", "missing_hole_cards").toString());
                return badRequest(ErrorCode.AI_INVALID_PARAMETERS);
            }
            // Execute AI analysis
            AIAnalysisResponse response = aiAnalysisOperator.performAIAnalysis(request);
            // Success response
            logger.info(log.put("analysisId", response.getAnalysisId())
                .put("hasRecommendation", response.getRecommendation() != null).put("op_rslt", "success").toString());
            return aiAnalysisSuccess(response);
        } catch (IllegalArgumentException e) {
            logger.warn(log.put("op_rslt", "validation_error").put("error", e.getMessage()).toString());
            return error(ErrorCode.AI_INVALID_PARAMETERS, e.getMessage());
        } catch (Exception e) {
            logger.error(log.put("op_rslt", "system_error").put("error", e.getMessage()).toString(), e);
            return serviceUnavailable(ErrorCode.AI_SERVICE_UNAVAILABLE);
        }
    }
}